%%%-------------------------------------------------------------------
%%% @author liuwentao
%%% @doc
%%%
%%% @end
%%% Created : 26. 7月 2021 11:15
%%%-------------------------------------------------------------------
-module(assets).
-author("liuwentao").

%% API
-export([
    init/0                  %% 初始化
    , gain_to_trigger/3     %% 获取资产获得触发器
    , loss_to_trigger/3     %% 获取失去触发器
    , get_role_assets/2     %% 获取对应资产数量
    , update_role_assets/3  %% 更新资产数量
    , pack_assets/3         %% 打包资产
]).

-include("common.hrl").
-include("assets.hrl").
-include("role.hrl").
-include("trigger.hrl").

%% @doc 资产初始化
init() ->
    #assets{init_flag = true}.

%% @doc 获取获得触发器
gain_to_trigger(Type, Val, R) when is_atom(Type) ->
    %% 获取资产id
    Id = assets_data:label_to_enum(Type),
    gain_to_trigger(Id, Val, R);
gain_to_trigger(?assets_diamonds, Val, R) -> #evt_gain_diamonds{val = Val, reason = R};
gain_to_trigger(?assets_gold, Val, R) -> #evt_gain_gold{val = Val, reason = R};
gain_to_trigger(?assets_stone_coin, Val, R) -> #evt_gain_stone_coin{val = Val, reason = R};
gain_to_trigger(?assets_exp, Val, R) -> #evt_gain_exp{val = Val, reason = R};
gain_to_trigger(_, _Val, _R) -> false.


%% @doc 获取失去
loss_to_trigger(Type, Val, R) when is_atom(Type) ->
    %% 获取资产id
    Id = assets_data:label_to_enum(Type),
    loss_to_trigger(Id, Val, R);
loss_to_trigger(?assets_diamonds, Val, R) -> #evt_loss_diamonds{val = Val, reason = R};
loss_to_trigger(?assets_gold, Val, R) -> #evt_loss_gold{val = Val, reason = R};
loss_to_trigger(?assets_stone_coin, Val, R) -> #evt_loss_stone_coin{val = Val, reason = R};
loss_to_trigger(?assets_exp, Val, R) -> #evt_loss_exp{val = Val, reason = R};
loss_to_trigger(_, _Val, _R) -> false.


%% @doc 获取对应资产数量
get_role_assets(#role{assets = Assets}, Id) ->
    get_role_assets(Assets, Id);
get_role_assets(#assets{assets_list = AssetsList}, Id) ->
    case lists:keyfind(Id, 1, AssetsList) of
        {Id, N} -> N;
        _ ->
            0
    end.

%% @doc 更新资产信息
update_role_assets(Role = #role{assets = Assets}, Id, NewVal) ->
    NewAssets = update_role_assets(Assets, Id, NewVal),
    Role#role{assets = NewAssets};
update_role_assets(Assets = #assets{assets_list = AssetsList}, Id, NewVal) when NewVal > 0 ->
    NewAssetsList =
        case lists:keyfind(Id, 1, AssetsList) of
            {Id, _} ->
                lists:keystore(Id, 1, AssetsList, {Id, NewVal});
            _ ->
                [{Id, NewVal} | AssetsList]
        end,
    Assets#assets{assets_list = NewAssetsList};
update_role_assets(Assets = #assets{assets_list = AssetsList}, Id, _NewVal) ->
    NewAssetsList = lists:keydelete(Id, 1, AssetsList),
    Assets#assets{assets_list = NewAssetsList}.


%% @doc 打包资产（客户端需要显示的资产,就打包进去)
pack_assets(#assets{assets_list = AssetsList}, all, _List) ->
    AssetsList;
pack_assets(#assets{assets_list = AssetsList}, _, List) ->
    [{Id, Num} || {Id, Num} <- AssetsList, lists:member(Id, List)].



